<script setup>
import { useRoute } from 'vue-router'
import { onMounted, reactive } from 'vue';
import { getNamespaceListHandler } from '../../api/namespace.js';
import { listClusterHandler } from '../../api/cluster.js';
import { toRefs } from 'vue';

const route = useRoute()

const props = defineProps({
  showNamespace: {
    type: Boolean,
    default: true
  },
  clusterReadonly: {
    type: Boolean,
    default: false
  },
  namespaceReadonly: {
    type: Boolean,
    default: false
  }
})

const data = reactive({
  clusterList: [],
  namespaceList: [],
  clusterId: "",
  namespace: ""
})

const emits = defineEmits(['clusterChangedRollback', 'namespaceChangedRollback'])

const namespaceChangedRollbackHandler = () => {
  emits('namespaceChangedRollback', data.clusterId, data.namespace)
}

const clusterChangedRollbackHandler = () => {
  emits('clusterChangedRollback', data.clusterId)
}

const getNamespaceList = async () => { // 查询集群列表
  console.log("查询集群:", data.clusterId)
  await getNamespaceListHandler(data.clusterId).then((response) => {
    console.log("response:", response.data.data.items)
    data.namespaceList = response.data.data.items
  })
  // const defaultNamespaceSelected = "default"
  const curNamespace = route.query.namespace
  data.namespace = curNamespace ? curNamespace : "default"
  namespaceChangedRollbackHandler()
}

const getClusterList = async () => {
  await listClusterHandler().then(
    (res) => {
      data.clusterList = res.data.data.items
    }
  )
}
const clusterChanged = () => {
  if (props.showNamespace) {
    getNamespaceList()
  } else {
    clusterChangedRollbackHandler()
  }
}

const namespaceChanged = () => {
  namespaceChangedRollbackHandler()
}
onMounted(async () => {
  await getClusterList()
  const defaultClusterSelected = data.clusterList[0].clusterId
  const curClusterId = route.query.clusterId
  data.clusterId = curClusterId ? curClusterId : defaultClusterSelected
  // 查询namespace
  clusterChanged()
  
})
const { clusterId,
        clusterList,
        namespace,
        namespaceList
      } = toRefs(data)

</script>

<template>
  <el-select
  filterable
  v-model="clusterId"
  placeholder="选择集群"
  @change="clusterChanged()"
  style="width: 180px;"
  :disabled="props.clusterReadonly">
    <el-option v-for="item in clusterList" :key="item.clusterId" :label="item.displayName" :value="item.clusterId"
      :disabled="item.status == 'InActive'"/>
  </el-select>

  <el-select
  filterable
  v-if="props.showNamespace"
  v-model="namespace"
  placeholder="选择namespace"
  @change="namespaceChanged()"
  style="width: 180px; margin-left: 10px;"
  :disabled="props.namespaceReadonly">
    <el-option v-for="item in namespaceList" :key="item.metadata.name" :label="item.metadata.name" :value="item.metadata.name"/>
  </el-select>
</template>

<style scoped></style>
